package com.example.yingjiguanli_demo.controller;

import com.example.yingjiguanli_demo.aspect.interfaces.RateLimiter;
import com.example.yingjiguanli_demo.aspect.interfaces.RequirePermission;
import com.example.yingjiguanli_demo.pojo.*;
import com.example.yingjiguanli_demo.service.IQuestionsService;
import com.example.yingjiguanli_demo.utils.UserUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author scj
 * @since 2024-11-04
 */
@RestController
@RequestMapping("api/v1/questions")
public class QuestionsController {
    @Autowired
    private IQuestionsService questionService;

    @Autowired
    private UserUtils userUtils;



    /**
     * 导入题目和选项
     * @param importRequest 包含题目和选项的请求对象
     * @return 导入结果
     */

    @ApiOperation(value = "导入题目模块")
    @RequirePermission("admin")
    @RateLimiter
    @PostMapping("/import")
    public Result<?> importQuestions(@RequestBody ImportRequest importRequest,@RequestParam Integer subjectId) {
        List<Questions> questions = importRequest.getQuestions();
        List<Options> options = importRequest.getOptions();

        // 调用 Service 层方法处理导入
        return questionService.importQuestions(questions, options,subjectId);
    }

    /***
     * excel导入题目模块
     * @param file excel
     * @param subjectId 科目id
     * @return 导入结果
     */
    @ApiOperation(value = "excel导入题目模块")
    @RequirePermission("admin")
    @RateLimiter
    @PostMapping("/excel/import")
    public Result<?> importQuestions(@RequestParam("file") MultipartFile file,@RequestParam Integer subjectId) {
        return questionService.importQuestionsFromExcel(file,subjectId);
    }

    /***
     * 获取题目列表
     * @param limit 获取题目数量
     * @param subjectId 科目id
     * @return 题目列表
     */
    @ApiOperation(value = "获取题目列表")
    @RequirePermission("user")
    @GetMapping("/fetch")
    public Result<List<Questions>> fetchQuestions(
            @RequestParam int limit
            ,@RequestParam int subjectId) {
        return questionService.getQuestionsForUser(subjectId,limit);
    }

    /***
     * 提交答案
     * @param sessionId sessionId
     * @param answerDTOs 答案列表
     * @return 提交结果
     */
    @ApiOperation(value = "提交答案")
    @RequirePermission("user")
    @PostMapping("/submit")
    public Result<List<AnswerResult>> submitAnswers(@CookieValue(name = "SESSIONID", required = false) String sessionId,
                                                    @RequestBody List<AnswerDTO> answerDTOs) {
        int userId = userUtils.getUserId(sessionId);

        // 提交答案并获取结果集合
        List<AnswerResult> results = questionService.checkAndRecordAnswers(userId, answerDTOs);

        return Result.success(results); // 返回所有答案的提交结果
    }


}
